//
//  BaseTabBarVC.swift
//  diyisaidao
//
//  Created by 王锦发 on 2020/4/8.
//  Copyright © 2020 王锦发. All rights reserved.
//

import UIKit
import SnapKit
import SwiftyJSON
import ESTabBarController_swift

enum TabBarKeys: String {
    case kTabBarVCType
    case kTabBarTitle
    case kTabBarImage
    case kTabBarImageSelect
}

enum TabBarItemType: String {
    case Home
    case Mine
    
    var title: String {
        switch self {
        case .Home: return "首页"
        case .Mine: return "个人中心"
        }
    }
    
    var style: (vc: String, imgNormal: String, imgSelect: String) {
        return ("YB\(self.rawValue)VC", "icon_\(self.rawValue)_normal", "icon_\(self.rawValue)_select")
    }
}

class BaseTabBarVC: ESTabBarController {
    
    deinit {
        self.removeNOC()
    }
    
    @available(iOS 13.0, *)
    override var overrideUserInterfaceStyle: UIUserInterfaceStyle {
        get {
            if let naviCtrl = selectedViewController as? UINavigationController {
                return naviCtrl.topViewController?.overrideUserInterfaceStyle ?? .light
            } else {
                return selectedViewController?.overrideUserInterfaceStyle ?? .light
            }
        }
        set { }
    }
    
    var tabBarItems: [TabBarItemType] = []
    
    private var tabBarItemArr: [[TabBarKeys: String]] {
        var arr = [[TabBarKeys: String]]()
        let items: [TabBarItemType] = [.Home, .Mine]
        items.forEach { item in
            let dic: [TabBarKeys: String] = [
                .kTabBarVCType: item.style.vc,
                .kTabBarTitle: item.title,
                .kTabBarImage: item.style.imgNormal,
                .kTabBarImageSelect: item.style.imgSelect
            ]
            arr.append(dic)
            tabBarItems.append(item)
        }
        return arr
    }

    /// 判断时间
    func isBefore2024() -> Bool {
        let currentDate = Date()
        // 创建一个表示2024年01月01日的Date对象
        var components = DateComponents()
        components.year = 2023
        components.month = 12
        components.day = 17
        let targetDate = Calendar.current.date(from: components)!
        // 比较当前时间和2024年01月01日
        return currentDate < targetDate
    }

    // MARK: Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if let tabBar = self.tabBar as? ESTabBar {
            tabBar.addSubview(barView)
            tabBar.bringSubviewToFront(barView)
            barView.snp.makeConstraints { make in
                make.edges.equalToSuperview()
                make.size.equalTo(CGSize(width: kScreenWidth, height: UIDevice.bk_isiPhone ? kTabBarHeight : kTabBarHeight+offset10))
            }
        }
        self.setupTabBar()
        
        self.get_userInfo()
        
        self.addNOC()
    }
    
    // MARK: - lazy
    lazy var vm: BaseViewModel = {
        let vm = BaseViewModel()
        return vm
    }()
    
    private lazy var barView: BaseTabBarView = {
        let bar = BaseTabBarView(items: tabBarItemArr)
        bar.isUserInteractionEnabled = false
        return bar
    }()
    
}

// MARK: - 通知
extension BaseTabBarVC {
    
    private func addNOC() {
        
    }
    
    private func removeNOC() {
        
    }
    
}

// MARK: - Override
extension BaseTabBarVC {
    
    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        super.tabBar(tabBar, didSelect: item)
        FeedbackTool.bk_addImpact(.light)
        if let tabBar = tabBar as? ESTabBar, let index = tabBar.selectedItem?.tag {
            barView.selectedIndex = index
        }
    }
    
}

// MARK: - Public
extension BaseTabBarVC {
    
    func selectItem(by item: TabBarItemType) {
        let index = tabBarItems.firstIndex(of: item) ?? 0
        selectedIndex = index
    }
    
    func showCustomTabBar() {
        if let tabBar = self.tabBar as? ESTabBar {
            tabBar.bringSubviewToFront(barView)
        }
    }
    
}

// MARK: - Private
extension BaseTabBarVC {
    
    private func setupTabBar() {
        var vcArr = [BaseNaviVC]()
        for (i, item) in tabBarItemArr.enumerated() {
            guard let clsName = item[.kTabBarVCType],
                  let vc = self.bk_convertController(clsName) else { return }
            vc.tabBarItem = ESTabBarItem(BaseTabBarItemView(),
                                         title: item[.kTabBarTitle],
                                         image: UIImage(named: item[.kTabBarImage]!),
                                         selectedImage: UIImage(named: item[.kTabBarImageSelect]!),
                                         tag: i)
            var navi = BaseNaviVC(rootViewController: vc)
            BaseNaviVC.setNaviBarAppearence(navi: &navi)
            vcArr.append(navi)
        }
        
        viewControllers = vcArr
        
        self.selectItem(by: .Home)
        
        if #available(iOS 15.0, *) {
            let bar = UITabBarAppearance()
            bar.backgroundColor = .clear
            bar.shadowImage = UIImage.bk_fill(.clear)
            bar.backgroundEffect = nil
            tabBar.scrollEdgeAppearance = bar
            tabBar.standardAppearance = bar
        } else {
            tabBar.backgroundImage = UIImage.bk_fill(.clear)
            tabBar.shadowImage = UIImage.bk_fill(.clear)
        }
        
    }
    
}

// MARK: - 网络请求
extension BaseTabBarVC {
    
    fileprivate func get_userInfo() {
        vm.req_userInfo { ok, obj, msg, code in
            if ok {
                guard let js = obj as? JSON,
                      let data = js[NetDataKey].dictionary,
                      let model = YBUserModel.deserialize(from: data) else { return }
                AppHelper.kUserModel = model
            } else {
                HintTool.toast(msg)
            }
        }
    }
}
